<template><!--团队排行-->
    <div id="test">
        <div style="background: var(--table-tr-hover-color);padding:10px;margin-top:10px;">
    <!--<title-top :fnlist="initObj.Fnlist"></title-top>-->
            总攻击得分 <Tag color="purple">{{scoreTotalStatics.totalAttackScore}}</Tag>
            <template v-if="[8, 9].includes(type)">总{{type === 8 ? '防守' : '运维' }}得分 <Tag color="purple">{{scoreTotalStatics.totalDefenseScore}}</Tag></template>
            <template v-if="[8].includes(type) && scoringType === 0">总防守失分 <Tag color="purple">{{scoreTotalStatics.totalDefenseLostScore}}</Tag></template>
            <template v-if="type === 8 && scoringType === 0">总重置失分 <Tag color="purple">{{scoreTotalStatics.totalResetLostScore}}</Tag></template>
            <template v-if="![8, 9].includes(type)">总防守失分 <Tag color="purple">{{scoreTotalStatics.totalDefenseScore}}</Tag></template>
            <template v-if="!(type === 8 && scoringType === 1)">总{{type === 9 ? "额外" : "异常"}}得分 <Tag color="purple">{{scoreTotalStatics.totalExceptScore}}</Tag></template>
            <template v-if="!(type === 8 && scoringType === 1)">总{{type === 9 ? "额外" : "异常"}}失分 <Tag color="purple">{{scoreTotalStatics.totalExceptLostScore}}</Tag></template>
    </div>
    <table-body :options="initObj"></table-body>
    <Modal v-model="scoreModal.show"
        :title="scoreModal.title"
        :mask-closable="false"
        @on-visible-change="visibleChange"
        width="400px">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="靶标" prop="target">
                    <Select filterable v-model="formValidate.target" placeholder="选择靶标"  filterable>
                        <Option v-for="item in targetAllotList" :key="item.id"  :value="JSON.stringify(item)" :title="item.targetName">{{item.targetName}}</Option>
                    </Select>
                </FormItem>
                <FormItem label="分数" prop="score">
                    <InputNumber v-model.trim="formValidate.score" :min="1" :max="1000" placeholder="输入分数"></InputNumber>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="scoreModal.show = false; scoreModal.loading = false; handleReset('formValidate')">取消</Button>
                <Button @click="saveScoreRecord('formValidate')" type="primary" :loading="scoreModal.loading">确定</Button>
            </div>
    </Modal>
    <report-grade ref="reportGrade" :type="type" :wpUpMode="wpUpMode"></report-grade>
    <package-progress
			:show="showProgress"
			:progress="progress"
			:status="progressStatus"
			@change="change"
			title="打包进度"
	></package-progress>
    <Modal
      v-model="uploadModal.show"
      @on-visible-change="visibleChange1"
      title="请选择靶标">
      <Form ref="formInline" :model="target" :rules="ruleInline" :label-width="56">
        <FormItem label="靶标" prop="targetId">
          <Select filterable v-model="target.targetId" filterable clearable placeholder=""
            @on-change="getTargetName" >
            <Option v-for="item in uploadModal.targetList" :value="item.id" :key="item.id" 
              :label="item.targetName.trim()" :title="item.targetName.trim()"></Option>
          </Select>
        </FormItem>
        <FormItem label="用户" prop="userId">
          <Select filterable v-model="target.userId" filterable clearable placeholder=""
            @on-change="getUserName" >
            <Option v-for="item in uploadModal.userList" :value="item.userId" :key="item.userId" 
              :label="item.userName.trim()" :title="item.userName.trim()"></Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer" class="footer">
        <Button @click="uploadModal.show = false;">取消</Button>
        <Upload  ref="upload"
          key="upload-new"
          class="form-upload"
          :action="uploadAction"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :on-format-error="handleFormatError"
          :on-exceeded-size="fileHasExceed"
          :on-progress="showTipModel"
          :on-success="addDefensePatch"
          :headers="uploadHeader"
          :format="['tar']"
          type="drag"
          footer-hide>
          <Button type="primary" :loading="uploadModal.loading" :disabled="isDisabled">确定</Button>
        </Upload>
      </div>
    </Modal>
    <Modal
      v-model="isShowTip"
      title=""
      :mask-closable="false"
      :width="300"
      class="tipModel"
    >
      <div class="ivu-modal-confirm-head">
        <div class="ivu-modal-confirm-head-icon" :class="submitSuccess?'ivu-modal-confirm-head-icon-success':'ivu-modal-confirm-head-icon-warning'">
          <i class="ivu-icon ivu-icon-ios-checkmark-circle"></i>
        </div>
        <div class="ivu-modal-confirm-head-title">{{showTipTitle}}</div></div>
    </Modal>
</div>
</template>
<script>
//	import Cookies from 'js-cookie'
import {adcTeamRankStatic,awdPlusTeamRankStatic,opTeamRankStatic,adcTeamScoreRecordTotal,awdPlusTeamScoreRecordTotal,saveScoreRecord,
    downloadSubmitAllReport, opTeamScoreRecordTotal, downloadSceneAllReport, hasReport} from '@/api/compitionStatic'
import {queryTargetAllot, ctfReport} from '@/api/drill_compete.js'
import { isAllowUploadDefenseFile, uploadDefenseFiles } from '@/api/drill'
import { getUserInstanceExclude } from '@/api/access_new'
import tableBody from './tableListComponent'
import groupMixin from "@/mixin/groupMixin";
import { getNumReg } from '@/libs/reg'
import ReportGrade from '@/components/report-grade'
import PackageProgress from '@/components/package-progress/package-progress.vue'

    export default {
    name: 'scenes',
    props:['sceneId','poll','type', 'basisScore','drillDetail', 'wpUpMode','drillStatus'],
        mixins: [groupMixin],
        inject: ['detailParent'],
    data(){
        const d = function(val){
            this.getRankingStatic(null,null,val)
        }.bind(this);

        return {
            isDisabled: false,
            isShowTip: false,
            submitSuccess: false,
            showTipTitle: '',
            uploadAction: "/api/minio/upload/permanent?visibility=company&type=files&bucket=files",
            uploadHeader: {
                Authorization: localStorage.getItem('token'),
                Accept:'*/*',
            },
            target: {
                targetId: ''
            },
            paramObj: {
                targetId: '',
                targetName: '',
                port: ''
            },
            ruleInline: {
                targetId: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                userId: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ]
            },
            uploadModal: {
                show: false,
                loading: false,
                targetList: [],
                userList: [],
                teamId: '',
                teamName: '',
                userId: '',
                userName: ''
            },
            progress: 0, // 进度
            progressStatus: 'active',
            showProgress: false, // 展示进度
            initObj:{
                Button:[
                ],
                Input:[
                ],
                Select:[
                    {
                        optionsValue: [],
                        placeholder: `请选择团队`,
                        fnName: this.getRankingStaticById
                    }
                ],
                DatePicker:{
                isShow:false,
                fnName:d,
                },
                Page:{
                    total:0,
                    currentPage:1,
                    pageSize:10
                },
                Table:{
                listCol:[
                    {
                   title:'排行',
    //                type: 'index',
                    align: 'center',
                    key:'rank',
    //                width:60,
                    placement:'top-right',
                    order:2,
                    render:(h,params) => {
                            let ele;
                            if(params.row._index < 3 && this.curPage == 1){
                                ele = h('img',{
                                    attrs:{
                                        src:require(`../../../../assets/scene/top${params.row._index+1}.png`)
                                    },
                                    style:{
                                        display:'inline-block',
    //		            				width:'20px',
                                        verticalAlign: 'text-bottom',
                                        marginLeft: '20px'
                                    }
                                })
                            }else{
                                ele = h('span',params.row._index+1 + (this.curPage-1)*10)
                            }
                            let index = params.row._index+1;
                            let color;
                            if(index == 1){
                                color = '#f34938';
                            }else if(index == 2){
                                color = '#eb8205';
                            }else if(index == 3){
                                color = '#27b666';
                            }else{
                                color = '#000'
                            }
                            return h('span',[
                                h('span',{
                                    style:{
                                        color:color
                                    }
                                },'排行'),
                                ele
                            ]);
                        }
                    },
                    {
                    title:'团队名称',
                    key:'teamName',
                    align:'center',
                    ellipsis:true,
                    tooltip:true,
                    placement:'top-left',
                    order:1,
                        width: 240
                    },
    //              {
    //                title:'势力方名称',
    //                key:'partyName',
    //                align:'center',
    //                ellipsis:true,
    //                tooltip:true,
    //              },
                    {
                        title:() => {
                            return this.type === 9 && this.showOpLastScoreTime ? '剩余分数' : '总分'
                        },
                        key:'totalScore',
                        align:'center',
                        ellipsis:true,
                        width:60
                    },
                    {
                        title:'最后失分时间',
                        key:'lastScoreTime',
                        align:'center',
                        ellipsis:true,
                        width:60,
                        show:() => {
                            return this.type === 9 && this.showOpLastScoreTime
                        }
                    },
                    {
                        title:'基础分',
                        key:'basisScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', this.basisScore || 5000)
                        },
                        show:() => {
                            return this.type === 8 && this.scoringType === 0
                        }
                    },
                    {
                        title:'攻击得分',
                        key:'attackScore',
                        align:'center',
                        width:60,
                    },
                    {
                        title:'防守失分',
                        key:'defenseScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.defenseScore||0)
                        },
                        show:() => {
                            return this.type == 1 || !this.type
                        }
                    },
                    {
                        title:'防守失分',
                        key:'defenseLostScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.defenseLostScore||0)
                        },
                        show:() => {
                            return [8].includes(this.type) && this.scoringType == 0
                        }
                    },
                    {
                        title:'防守得分',
                        key:'defenseScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.defenseScore||0)
                        },
                        show:() => {
                            return [8].includes(this.type)
                        }
                    }, 
                    {
                        title:'运维得分',
                        key:'defenseScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.defenseScore||0)
                        },
                        show:() => {
                            return [9].includes(this.type)
                        }
                    },
                    {
                        title:'重置失分',
                        key:'resetLostScore',
                        align:'center',
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.resetLostScore||0)
                        },
                        show:() => {
                            return this.type === 8 && this.scoringType === 0
                        }
                    },
                    {
                        title:'额外得分',
                        key:'exceptScore',
                        align:'center',
                        ellipsis:true,
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.exceptScore||0)
                        },
                        show:() => {
                            return this.type === 9
                        }
                    },
                    {
                        title:'异常得分',
                        key:'exceptScore',
                        align:'center',
                        ellipsis:true,
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.exceptScore||0)
                        },
                        show:() => {
                            return this.type === 1 || (this.type === 8 && this.scoringType === 0) || !this.type
                        }
                    },
                    {
                        title:'异常失分',
                        key:'exceptLostScore',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.exceptLostScore||0)
                        },
                        show:() => {
                            return this.type === 1 || (this.type === 8 && this.scoringType === 0)  || !this.type
                        }
                    },
                    {
                        title:'额外失分',
                        key:'exceptLostScore',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                        width:60,
                        render:(h,params)=>{
                            return h('span', params.row.exceptLostScore||0)
                        },
                        show:() => {
                            return this.type == 9
                        }
                    },
                    {
                        title:'是否提交报告',
                        key:'report',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                        placement:'top-right',
                        render:(h,params) => {
                            return h('Tag',{
                                props:{
                                    color:params.row.fileIds && params.row.fileIds.length ? 'var(--status-yes)' : 'var(--status-no)'
                                }
                            },params.row.fileIds && params.row.fileIds.length ? '是': '否')
                        },
                        show:() => {
                            return this.type == 9
                        }
                    },
                    {
                        title:'操作',
                        key:'action',
                        placement:'top-right',
                        show:() => {
                            return !this.poll || this.type === 8 || this.type === 9
                        },
                        opList:[
                            {
                                txt:'加分',
                                // disabled:this.disabledAllBtn,
                                show:() => {
                                    return this.poll ? false : true
                                },
                                on:{
                                    click:(data)=>{//4
                                        this.scoreType = 4;
                                        this.scoreModal.title = '团队加分';
                                        this.queryTargetAllot(data.teamId);
                                    }
                                }
                            },
                            {
                                txt:'减分',
                                // disabled:this.disabledAllBtn,
                                show:() => {
                                    return this.poll ? false : true
                                },
                                on:{
                                    click:(data)=>{//3
                                        this.scoreType = 3;
                                        this.scoreModal.title = '团队减分';
                                        this.queryTargetAllot(data.teamId)
                                    }
                                }
                            },
                            {
                                txt:'上传防御补丁',
                                show:() => {
                                    return this.type === 8
                                },
                                disabled: () => {
                                    return this.drillStatus == 3
                                },
                                on:{
                                    click:(data)=>{
                                        this.showUploadModal(data.teamId, data.teamName)
                                    }
                                }
                            },
                            {
                                txt:'下载',
                                show:() => {
                                    return this.drillDetail && [9].includes(Number(this.drillDetail.type))
                                },
                                disabled:(data) =>  !(data.fileIds && data.fileIds.length),
                                fun:this.downloadTeamAllReport
                            },
                            {
                                txt:'预览',
                                show:() => {
                                    return this.drillDetail && [9].includes(Number(this.drillDetail.type))
                                },
                                disabled:(data) =>  !(data.fileIds && data.fileIds.length),
                                fun:(data) => {
                                    window.open(`/api/minio/filePreview?id=${data.fileIds[0]}`);
                                }
                            },
                            {
                                txt:'题目信息',
                                show:() => {
                                    return this.drillDetail && [2, 4, 7, 9].includes(Number(this.drillDetail.type))
                                },
                                fun:(data) => {
                                    this.$refs.reportGrade.show(data.teamId,data.fileIds && data.fileIds.length,data.teamName)
                                }
                            },
                        ],
                        // render:(h,params) => {
                        //     return h('div',[
                        //         h('Button',{
                        //         props:{
                        //             type:'primary',
                        //             size:'small',
                        //         },
                        //         style:{
                        //             marginRight:'5px',
                        //             display:this.poll ? 'none' : 'inline-block'
                        //         },
                        //         on:{
                        //             click:()=>{//4
                        //                 this.scoreType = 4;
                        //                 this.scoreModal.title = '团队加分';
                        //                 this.queryTargetAllot(params.row.teamId);
                        //             }
                        //         }
                        //         },'加分'),
                        //         h('Button',{
                        //         props:{
                        //             type:'primary',
                        //             size:'small',
                        //         },
                        //         style:{
                        //             marginRight:'5px',
                        //             display:this.poll ? 'none' : 'inline-block'
                        //         },
                        //         on:{
                        //             click:()=>{//3
                        //                 this.scoreType = 3;
                        //                 this.scoreModal.title = '团队减分';
                        //                 this.queryTargetAllot(params.row.teamId)
                        //             }
                        //         }
                        //         },"减分"),
                        //     ])
                        // }
                    },
                ],
                listData:[]
                },
                Fnlist:'getRankingStatic',
            },
    //      sencenId:'',
            selName:'',
            timeout:{},
            curPage:1,
            scoreTotalStatics:{},
            targetAllotList:[],
            scoreModal:{
                show:false,
                loading:false,
                title:'团队加分'
            },
            formValidate:{
                target:'',
                score:1
            },
            ruleValidate:{
                target:[
                    { required: true, message: '请选择靶标', trigger: 'change'}
                ],
                score:[
                    { required: true, type:'number',message: '请输入大于0的数字', trigger: 'change'},
                    { validator: getNumReg(1000), trigger: 'change' }
                ]
            },
            showOpLastScoreTime:false
        }
    },
    computed:{
        scoringType() {//0  混合计分模式  1单独计分模式
            console.log(this.detailParent)
			return this.detailParent.scoringType || 0;
		}
    },
    components:{
//    'title-top':titleTop,
        'table-body':tableBody,
        ReportGrade,
        PackageProgress
    },
    watch:{
        teamList(newValue) {
            this.initObj.Select[0].optionsValue = newValue
        }
    },
    created(){
    //this.getRankingStatic();
    },
    beforeDestroy(){
        clearTimeout(this.timeout)
    },
    mounted(){
        this.$store.dispatch('common/getSysConfigShow','showOpLastScoreTime').then(data => {
            this.showOpLastScoreTime = data
        })
        this.hasReport()
        this.getRankingStatic();
        this.adcTeamScoreRecordTotal();
        if([1].includes(this.type)){
            this.initObj.Button.push({
                name:'导出排行',
                fnName: this.exportFile
            })
        }
        if ([8, 9].includes(this.type)) {
            this.initObj.Button.push({
                name:'导出排行',
                fnName: this.exportFile
            }, {
                name:'导出得分记录',
                fnName: this.exportScoreRecord
            }, {
                name:'打包下载所有报告',
                fnName: this.downloadAllReport,
                disabled: true
            })
            // let index = this.initObj.Table.listCol.findIndex(item => item.title === '防守失分')
            // if (index !== -1) { //
            //     this.initObj.Table.listCol.splice(index, 1, {
            //         title:'防守得分',
            //         key:'defenseScore',
            //         align:'center',
            //         width:60,
            //         render:(h,params)=>{
            //             return h('span', params.row.defenseScore||0)
            //         }
            //     }, {
            //         title:'防守失分',
            //         key:'defenseLostScore',
            //         align:'center',
            //         width:60,
            //         render:(h,params)=>{
            //             return h('span', params.row.defenseLostScore||0)
            //         }
            //     })
            // }
            // if (this.type === 8) { 
            //     index = this.initObj.Table.listCol.findIndex(item => item.title === '异常得分')
            //     if (index !== -1) {
            //         this.initObj.Table.listCol.splice(index, 0, {
            //             title:'重置失分',
            //             key:'resetLostScore',
            //             align:'center',
            //             width:60,
            //             render:(h,params)=>{
            //                 return h('span', params.row.resetLostScore||0)
            //             }
            //         })
            //     }
            //     this.initObj.Table.listCol.splice(3, 0, {
            //         title:'基础分',
            //         key:'basisScore',
            //         align:'center',
            //         width:60,
            //         render:(h,params)=>{
            //             return h('span', this.basisScore || 5000)
            //         }
            //     })
            //     // index = this.initObj.Table.listCol.findIndex(item => item.title === '操作')
            //     // if (index !== -1) {
            //     //     this.initObj.Table.listCol.splice(index, 1, {
            //     //         title:'操作',
            //     //         action:true,
            //     //         placement:'top-right',
            //     //         render:(h,params) => {
            //     //             return h('div',[
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px',
            //     //                     display:this.poll ? 'none' : 'inline-block'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{//4
            //     //                         this.scoreType = 4;
            //     //                         this.scoreModal.title = '团队加分';
            //     //                         this.queryTargetAllot(params.row.teamId);
            //     //                     }
            //     //                 }
            //     //                 },'加分'),
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px',
            //     //                     display:this.poll ? 'none' : 'inline-block'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{//3
            //     //                         this.scoreType = 3;
            //     //                         this.scoreModal.title = '团队减分';
            //     //                         this.queryTargetAllot(params.row.teamId)
            //     //                     }
            //     //                 }
            //     //                 },"减分"),
                                
            //     //                 h('Button',{
            //     //                     props:{
            //     //                         type:'primary',
            //     //                         size:'small',
            //     //                         disabled: this.drillStatus==3
            //     //                     },
            //     //                     on:{
            //     //                         click:()=>{
            //     //                             this.showUploadModal(params.row.teamId, params.row.teamName)
            //     //                         }
            //     //                     }
            //     //                 }, '上传防御补丁')
            //     //             ])
            //     //         }
            //     //     })
            //     // }
            // }
            // if (this.type === 9) {  // 9不要异常得分
            //     index = this.initObj.Table.listCol.findIndex(item => item.title === '异常得分')
            //     if (index !== -1) {
            //         this.initObj.Table.listCol.splice(index, 1, {
            //             title:'额外得分',
            //             key:'exceptScore',
            //             align:'center',
            //             ellipsis:true,
            //             width:60,
            //             render:(h,params)=>{
            //                 return h('span', params.row.exceptScore||0)
            //             }
            //         })
            //     }
            //     index = this.initObj.Table.listCol.findIndex(item => item.title === '防守得分')
            //     if (index !== -1) {
            //         this.initObj.Table.listCol.splice(index, 1, {
            //             title:'运维得分',
            //             key:'defenseScore',
            //             align:'center',
            //             width:60,
            //             render:(h,params)=>{
            //                 return h('span', params.row.defenseScore||0)
            //             }
            //         })
            //     }
            //     index = this.initObj.Table.listCol.findIndex(item => item.title === '防守失分')
            //     if (index !== -1) {
            //         this.initObj.Table.listCol.splice(index, 1)
            //     }
            //     index = this.initObj.Table.listCol.findIndex(item => item.title === '异常失分')
            //     if (index !== -1) {
            //         this.initObj.Table.listCol.splice(index, 1, {
            //             title:'额外失分',
            //             key:'exceptLostScore',
            //             align:'center',
            //             ellipsis:true,
            //             tooltip:true,
            //             width:60,
            //             render:(h,params)=>{
            //                 return h('span', params.row.exceptLostScore||0)
            //             }
            //         },
            //         {
            //             title:'是否提交报告',
            //             key:'report',
            //             align:'center',
            //             ellipsis:true,
            //             tooltip:true,
            //             placement:'top-right',
            //             render:(h,params) => {
            //                 return h('Tag',{
            //                     props:{
            //                         color:params.row.fileIds && params.row.fileIds.length ? 'var(--status-yes)' : 'var(--status-no)'
            //                     }
            //                 },params.row.fileIds && params.row.fileIds.length ? '是': '否')
            //             }
            //         })
            //     }
            //     // index = this.initObj.Table.listCol.findIndex(item => item.title === '操作')
            //     // if (index !== -1) {
            //     //     this.initObj.Table.listCol.splice(index, 1, {
            //     //         title:'操作',
            //     //         action:true,
            //     //         placement:'top-right',
            //     //         render:(h,params) => {
            //     //             return h('div',[
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px',
            //     //                     display:this.poll ? 'none' : 'inline-block'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{//4
            //     //                         this.scoreType = 4;
            //     //                         this.scoreModal.title = '团队加分';
            //     //                         this.queryTargetAllot(params.row.teamId);
            //     //                     }
            //     //                 }
            //     //                 },'加分'),
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px',
            //     //                     display:this.poll ? 'none' : 'inline-block'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{//3
            //     //                         this.scoreType = 3;
            //     //                         this.scoreModal.title = '团队减分';
            //     //                         this.queryTargetAllot(params.row.teamId)
            //     //                     }
            //     //                 }
            //     //                 },"减分"),
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                     disabled: !(params.row.fileIds && params.row.fileIds.length)
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{
            //     //                         this.downloadTeamAllReport(params.row)
            //     //                     }
            //     //                 }
            //     //                 },'下载'),
            //     //                 h('Button',{
            //     //                 props:{
            //     //                     type:'primary',
            //     //                     size:'small',
            //     //                     disabled: !(params.row.reportIds && params.row.reportIds.length)
            //     //                 },
            //     //                 style:{
            //     //                     marginRight:'5px'
            //     //                 },
            //     //                 on:{
            //     //                     click:()=>{
            //     //                         //新的预览接口
            //     //                         window.open(`/api/minio/filePreview?id=${params.row.fileIds[0]}`);
            //     //                         return;
            //     //                     }
            //     //                 }
            //     //                 },"预览"),
            //     //                 h('Button',{
            //     //                     props:{
            //     //                         type:'primary',
            //     //                         size:'small',
            //     //                     },
            //     //                     style:{
            //     //                         marginRight:'5px',
            //     //                         width:'60px',
            //     //                         display: [2, 4, 7, 9].includes(Number(this.drillDetail.type)) ? 'inline-block' : 'none'
            //     //                     },
            //     //                     on:{
            //     //                         click:()=>{
            //     //                             this.$refs.reportGrade.show(params.row.teamId, params.row.fileIds && params.row.fileIds.length,params.row.teamName)
            //     //                         }
            //     //                     }
            //     //                 }, '题目信息')
            //     //             ])
            //     //         }
            //     //     })
            //     // }
            // }
        }
    },
methods:{
    // 上传访问脚本成功，添加数据
    addDefensePatch({ code, data, info = {}, message }) {
      if (code !== 1) {
        this.$Message.warning(message)
        return
      }
      let filePath = data
      let fileId = info.id
      let fileName = info.originalName
      let params = {
        fileId,
        fileName,
        filePath,
        projectId: this.$route.query.prjid,
        sceneId: this.$route.query.id,
        teamId: this.uploadModal.teamId,
        teamName: this.uploadModal.teamName,
        userId: this.uploadModal.userId,
        userName:this.uploadModal.userName,
        targetId: this.paramObj.targetId,
        targetName: this.paramObj.targetName,
        port: this.paramObj.port
      }
      uploadDefenseFiles(params).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        this.$Message.info('上传防御补丁成功')
        this.uploadModal.show = false
        this.isShowTip = false
      }).catch(() => {
        this.$Message.error('添加防御补丁记录异常')
      })
    },
    getUserName(val) {
        if (val === undefined) {
            return
        }
        this.uploadModal.userId = val
        let template = this.uploadModal.userList.find(item => item.userId === val) || {}
        this.uploadModal.userName = template.userName
    },
    // 获取靶标名称
    getTargetName(val) {
      if (val === undefined) {
        return
      }
      this.paramObj.targetId = val
      let template = this.uploadModal.targetList.find(item => item.id === val) || {}
      this.paramObj.targetName = template.targetName
      this.paramObj.port = template.defensivePort
      let params = {
        projectId: this.$route.query.prjid,
        sceneId: this.$route.query.id,
        teamId: this.uploadModal.teamId,
        teamName: this.uploadModal.teamName,
        userId: this.uploadModal.userId,
        userName:this.uploadModal.userName,
        targetId: val,
        targetName: template.targetName
      }
      this.uploadModal.loading = true
      isAllowUploadDefenseFile(params).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          this.isDisabled = true
          return
        }
        this.isDisabled = false
      }).catch(() => {
        this.isDisabled = true
        this.$Message.error('查看是否允许上传异常')
      }).finally(() => {
        this.uploadModal.loading = false
      })
    },
    beforeUpload(file){
        // const fileSize = file.size / 1024 / 1024 > this.$store.state.common.fileMax;
        // if(fileSize){
        // this.$Message.error({
        //     content: `文件大小不能大于${this.$store.state.common.fileMax}M`,
        //     duration: 2
        // });
        // return false;
        // }
      let name = file.name.split('.')[0];
      let reg = /^[0-9a-zA-Z_\u4e00-\u9fa5]*$/;
      if(!reg.test(name)){
      this.$Message.warning('文件名只能包含数字，字母，汉字和下划线')
        return false
      }
      if(name.length>50){
      this.$Message.warning('文件名的长度不能超过50')
        return false
      }
      this.file = file
    },
    handleFormatError(){
      this.$Message.warning('文件格式错误，请上传tar类型的压缩文件')
    },
    fileHasExceed(){
      this.$Message.warning('请上传10M以内的文档')
      this.submitSuccess = false;
    },
    showTipModel(event){
      this.isShowTip = true;
      this.submitSuccess = true;
      this.showTipTitle=`文件已上传${parseInt(event.percent)}%，请稍后...`;
    },
    showUploadModal(teamId, teamName) {
        this.uploadModal.show = true
        this.uploadModal.loading = true
        this.uploadModal.teamId = teamId
        this.uploadModal.teamName = teamName
        this.uploadModal.targetList = []
        let params = {
            pageIndex:1,
            pageSize: 2147483646,
            sceneId:this.$route.query.id,
            projectId:this.$route.query.prjid,
            teamId
        }
        queryTargetAllot(params).then(data => {
            if(data.code == 1){
                this.uploadModal.targetList = data.data.items;
            }else{
                this.$Message.warning(data.message);
            }
        }).catch(() => {
            this.$Message.error('查询题目分配异常');
        })
        getUserInstanceExclude({
            testId:this.$route.query.id,
            pageIndex: 1,
            pageSize: 2147483646,
            accessGroupId: teamId
        }).then(({ code, data = {}, message }) => {
            if (code !== 1) {
                this.$Message.warning(message)
                return
            }
            this.uploadModal.userList = data.data || []
        }).finally(() => {
            this.uploadModal.loading = false
        })

    },
    hasReport() {
        hasReport(this.$route.query.id).then(({code, data, message}) => {
        if (code !== 1) {
            this.$Message.warning(message)
        } else {
            this.initObj.Button.forEach(item => {
                if (item.name === '打包下载所有报告') {
                    this.$set(item, 'disabled', !data)
                }
            })
        }
        }).catch(error => {
            this.$Message.error('查询是否存在解题报告异常')
        })
    },
    change(val) {
	  	this.showProgress = val
    },
    downFileProgress(progress){
        let currentProgress = progress.loaded * 1; //B单位
        if (this.total) {
            this.total += currentProgress
        } else {
            this.total = currentProgress
        }
        currentProgress = this.total - currentProgress ? currentProgress : currentProgress / 2;
        let rate = (((this.total-currentProgress)/this.total)*100).toFixed(2)*1;
        if(!this.rate || rate > this.rate){
            this.progress = rate;
        }
    },
    // 导出排名统计
    exportFile(){
	  	let sceneId = this.$route.query.id;
	  	let sceneName = this.$route.query.name;
	  	let a = document.createElement("a");
	    document.body.appendChild(a);
	    a.href = this.type === 1 ? `/api/compete/teamScoreRecord/exportGF/${sceneId}/${sceneName}` : this.type === 8 ? `/api/compete/teamScoreRecord/exportAwdPlus/${sceneId}/${sceneName}` : `/api/compete/teamScoreRecord/exportYW/${sceneId}/${sceneName}`;
        a.download = ''; //命名下载名称
	    a.click(); //点击触发下载
	    a.remove();
	},
    // 导出得分记录
	exportScoreRecord(){
		let sceneId = this.$route.query.id;
	  	let sceneName = this.$route.query.name;
	  	let a = document.createElement("a");
	    document.body.appendChild(a);
        a.href = this.type === 8 ? `/api/compete/userSubmitRecord/exportAwdPlus/${sceneId}/${sceneName}` : `/api/compete/userSubmitRecord/exportYW/${sceneId}/${sceneName}`;
	    a.download = ''; //命名下载名称
	    a.click(); //点击触发下载
	    a.remove();
	},
    downloadAllReport(){
    	let sceneId = this.$route.query.id;
    	this.showProgress = true
    	downloadSceneAllReport(sceneId,[],this.downFileProgress).then(data => {
			this.total = 0
    		if(data.type == 'application/octet-stream'){
                const downloadElement = document.createElement("a");
                const href = window.URL.createObjectURL(data);
                downloadElement.href = href;
                downloadElement.download = '解题报告.zip';
                document.body.appendChild(downloadElement);
                downloadElement.click();
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
    		}else{
    			this.$Message.error('下载报告失败!不存在文件数据！');
    		}
    	}).catch(error => {
    		this.progressStatus = 'wrong'
    		this.$Message.error('下载报告失败!');
    	}).finally(() => {
			this.progress = 100
    		setTimeout(() => {
				this.showProgress = false
				this.progressStatus = 'active'
				this.progress = 0
			}, 2000)
		})
    },
    downloadTeamAllReport(data){
        let sceneId = this.$route.query.id;
        let teamName = data.teamName;
        this.showProgress = true
        downloadSubmitAllReport(sceneId,data.teamName,data.reportIds, this.downFileProgress).then(data => {
            if(data.type == 'application/octet-stream'){
                const downloadElement = document.createElement("a");
                const href = window.URL.createObjectURL(data);
                downloadElement.href = href;
                downloadElement.download = `${teamName}_解题报告.zip`;
                document.body.appendChild(downloadElement);
                downloadElement.click();
                document.body.removeChild(downloadElement); // 下载完成移除元素
                window.URL.revokeObjectURL(href); // 释放掉blob对象
            }else{
                this.$Message.error('下载报告失败!不存在文件数据！');
            }
        }).catch(error => {
            this.progressStatus = 'wrong'
            this.$Message.error('下载报告失败!');
        }).finally(() => {
			this.progress = 100
    		setTimeout(() => {
				this.showProgress = false
				this.progressStatus = 'active'
				this.progress = 0
			}, 2000)
		})
    },
    getRankingStaticById(id){
        this.selName = this.getTeamNameById(id);
        this.getRankingStatic();
    },
    getRankingStatic(page,pageSize,querytime){
        let _this = this;
        let pages = page || 1;
        this.$set(this.initObj.Page, 'currentPage', pages)
        let rows = pageSize||_this.PZ|| 10;
        let id = '';
        let params={
            pageIndex : pages,
            pageSize : rows
        };
        this.curPage = pages;
        if(this.selName){
            params.teamName =  this.selName;
        }
        //if(querytime){
            //params.createtime = querytime[0];
            //params.lastupdatetime = querytime[1];
        //}
        if(_this.$route.query.id){
            let api = [8].includes(this.type) ? awdPlusTeamRankStatic : this.type === 9 ? opTeamRankStatic : adcTeamRankStatic
            api(this.$route.query.id,params).then(data=>{
            if(data.code==1){
                let listData = data.data.items;
                let proArr = listData.map(async item => {
                    this.$set(item,'fileId','');
                    this.$set(item,'fileName','');
                    await this.ctfReport(item);
                })
                Promise.all(proArr).then(data => {
                    _this.initObj.Table.listData = listData;
                })
                _this.initObj.Page.total = data.data.total;
                clearTimeout(this.timeout)
                if(this.poll){ //如果需要轮询
                    this.timeout = setTimeout(() => {
                        this.getRankingStatic(page,pageSize);
                    },3000)
                }
            }
            })
        }
    },
    ctfReport(item){
		return new Promise(resolve => {
	   	    let sceneId = this.$route.query.id;
	   	    let teamId = item.teamId;
	   	    ctfReport(sceneId,teamId).then(data => {
		   	  	if(data.code == 1 && data.data){
		   	  		this.$set(item,'reportIds',data.data.map(file =>file.id));
		   	  		this.$set(item,'fileIds',data.data.map(file =>file.fileId));
		   	  		this.$set(item,'fileNames',data.data.map(file =>file.fileName));
		   	  		resolve(true);
		   	  	}else{
		   	  		resolve(false);
		   	  	}
	   	    }).catch(error => {
	   	    	resolve(false);
	   	    })
	    })
    },
    saveInfo(val){
    },
    adcTeamScoreRecordTotal(){
        let sceneId = this.$route.query.id;
        let api = [8].includes(this.type) ? awdPlusTeamScoreRecordTotal : this.type === 9 ? opTeamScoreRecordTotal : adcTeamScoreRecordTotal
        api(sceneId).then(data => {
            if(data.code == 1){
                this.scoreTotalStatics = data.data.items;
            }else{
                this.$Message.error(data.message)
            }
        }).catch(() => {
            this.$Message.error('获取所有团队的总分统计信息失败')
        })
    },
    queryTargetAllot(teamId){
        let params = {
            pageIndex:1,
            pageSize: 2147483646,
            sceneId:this.$route.query.id,
            projectId:this.$route.query.prjid,
            teamId:teamId
        }
        queryTargetAllot(params).then(data => {
            if(data.code == 1){
                this.targetAllotList = data.data.items;
            }else{
                this.$Message.warning(data.message);
            }
        }).catch(() => {
            this.$Message.error('查询题目分配异常');
        })
        this.scoreModal.show = true;
        this.handleReset('formValidate');
    },
    visibleChange(type) {
        if (type) { // 打开模态框，立刻允许按钮点击
            this.scoreModal.loading = false
        } else { // 关闭模态框时，延迟使按钮点击，避免多次提交
            setTimeout(() => {
                this.scoreModal.loading = false
            }, 1000)
        }
    },
    visibleChange1(type) {
      if (!type) {
        this.$refs.formInline.resetFields();
      }
    },
    saveScoreRecord(){
        this.scoreModal.loading = true
        this.$refs['formValidate'].validate((valid) => {
            if(valid){
                let target = JSON.parse(this.formValidate.target);
                let data = {
                "projectId": this.$route.query.prjid,
                "sceneId": this.$route.query.id,
                "score": this.formValidate.score,
                "scoreType": this.scoreType,
                "targetId": target.id,
                "targetName":  target.targetName,
                "teamId": target.teamId,
                "teamName": target.teamName
                }
                saveScoreRecord(data).then(data => {
                    if(data.code == 1){
                        this.$Message.info('操作成功');
                        this.scoreModal.show = false;
                        this.getRankingStatic();
                        this.adcTeamScoreRecordTotal();
                    }else{
                        this.cancelLoading('scoreModal');
                        this.$Message.warning(data.message);
                    }
                }).catch(() =>{
                    this.$Message.error('操作异常')
                    this.cancelLoading('scoreModal');
                })
            }else{
                this.cancelLoading('scoreModal');
            }
        })
    },
    handleReset(name) {
        this.formValidate = {
            target:'',
            score:1
        }
        this.$refs[name].resetFields();
//      this.$refs [name].fields.forEach(function (e) {
//		      if (e.fieldValue != undefined && e.fieldValue!='') {
//		          e.resetField()
//		      }
//		})
    },
    cancelLoading(name){
        this[name].loading = false;
    },
},
}
</script>

<style>
.drillsTable .ivu-poptip-body {
    text-align: left!important;
}
.scenesHeader{
    margin-bottom: 16px;
}
.drillTables{
    min-height: 300px;
}
.drillsTable.ivu-table-wrapper{
    overflow: inherit;
}
</style>
<style scoped>
.Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
}
.targetHeader{
    padding: 10px;
    margin-bottom: 10px;
}
.form-upload {
  margin-left: 12px;
  width: fit-content;
  float: right;
}
.form-upload /deep/ .ivu-upload {
  border: none !important;
}
</style>
